package com.pine.dbant.plugin.sqlite;

import com.pine.dbant.common.model.ConnectionInfo;
import com.pine.dbant.common.plugin.JdbcConnector;
import com.pine.dbant.common.plugin.QueryExecuteParams;
import com.pine.sunflower.core.plugin.Configuration;
import com.pine.sunflower.core.utils.Strings;
import org.apache.commons.lang3.StringUtils;

import java.sql.Connection;
import java.util.Set;

/**
 * @author xiaoyuan
 * @create 2022/11/29 15:58
 **/
public class SqliteConnector  extends JdbcConnector {
    public SqliteConnector(Configuration configuration, Connection connection, ConnectionInfo connectionInfo) {
        super(configuration, connection, connectionInfo);
    }


    @Override
    public String formatSql(QueryExecuteParams params) {
        String sqlFormat = "select * from ({}) {} {} {}";
        if (StringUtils.isNotBlank(params.getWhereCriteria())) {
            sqlFormat = "{} {} {} {}";
        }
        String where = " where " + params.getWhereCriteria();
        String order = "order by " + params.getOrderCriteria();
        String pageSql = getPageSql(params);
        return Strings.format(sqlFormat, params.getScript(), StringUtils.isBlank(params.getWhereCriteria()) ? "" : where, StringUtils.isBlank(params.getOrderCriteria()) ? "" : order,
                pageSql);
    }

    @Override
    public String getPageSql(QueryExecuteParams params) {
        int limitFrom = (params.getPageIndex() - 1) * params.getPageSize();
        return params.isNoPage() ? "" : " limit " + params.getPageSize() + " Offset " + limitFrom;
    }

    @Override
    public void configQueryCommandType(Set<String> queryCommandTypes) {
        queryCommandTypes.add("PRAGMA");
    }
}
